<?php
/**
 * Created by PhpStorm.
 * userValidate: hms
 * Date: 2018/8/7
 * Time: 9:27
 */

namespace app\mini\controller;

use think\Controller;
use think\Config;
use redis\Redis;
use think\Db;
use think\Request;
use think\Session;
use app\mini\model\Member;
use app\mini\validate\userValidate;
use app\Tools\VerifyCodeImage;
use app\index\model\Lookinto;
use app\index\model\YingMu;

class Login extends Controller
{
    const LOGIN_MOBILE=[
        15845838498,
        18864862406,
        13643815855,
        13616317978,
        18102682813,
        15246188965,
        15878893931,
        13244017356,
        18149562098,
        18184209423,
        15811754434,
        13904169121,
        15564660077,
        13978691312,
        18934672286,
        13647066719,
        15093305195,
        15069088849,
        13604895042,
        18249743988,
        13548552465,
        18965953480,
        13704983639,
        18648505777,
        13681498733,
        18670544668,
        13758990750,
        13042588258,
        15937127808,
        15050312816,
        18346623260,
        13851472572,
        17638882323,
        13974205018,
        13591000987,
        15954631007,
        13601029920,
        18710081099,
        13912251421,
        17779260117,
        13977235861,
        13797402308,
        13892898203,
        18100887996,
        18530902861,
        18099146067,
        13919908929,
        15838589729,
        18634550502,
        18366611091,
        15524402149,
        13275871919,
        18806355000,
        13676700332,
        15234716842,
        15139178056,
        18858959792,
        18657556613,
        15923430843,
        15139937620,
        15168707311,
        18358513388,
        18698426276,
        15546470626,
        18680866654,
        13964994777,
        18603352970,
        13246928236,
        13368593313,
        15935931332,
        13580506460,
        15356203270,
        18748145549,
        13407504308,
        13359353763,
        15711091142,
        18503898055,
        13835624918,
        13958076048,
        13548625619,
        13906522615,
        13918776512,
        15757482022,
        15895270943,
        13644088898,
        13790887098,
        15715801060,
        18530950380,
        13983538292,
        18753429119,
        15216533567,
        18653064133,
        13332893830,
        13808971547,
        13588027755,
        18007556896,
        15138674011,
        13148848731,
        18530062200,
        15576155878,
        18818778711,
        15899666186,
        18638902812,
        15046703085,
        13126642156,
        13891959519,
        13951531976,
        13750807740,
        15138988708,
        15979106473,
        13598875946,
        13588103951,
        13738003970,
        13323393528,
        15004218065,
        18132995520,
        18916755017,
        18996482118,
        13305934818,
        15813674330,
        13739075467,
        13007628716,
        13257596349,
        17321080817,
        17701836617,
        13867105912,
        15517071876,
        18615453789,
        18550351520,
        18550323541,
        16715127788,
        15210677808,
        13963516896,
        17359502099,
        13227592740,
        15893058475,
        15955405778,
        13386538577,
        13350258025,
        18117050617,
        18665108008,
        15867333362,
        15841364656,
        18773254884,
        15319358738,
        13812966351,
        13819150165,
        13592501014,
        18657156800,
        18953699743,
        15645956277,
        15052782776,
        15336873218,
        15122267996,
        18628223375,
        17605010507,
        18653095180,
        18078325121,
        13519143565,
        18007806178,
        13967928321,
        15925851677,
        13471942465,
        13577194047,
        15968821285,
        13738199465,
        13455060111,
        13986311841,
        18665108089,
        13920509152,
        13263861847,
        18918936426,
        15017093646,
        18918077197,
        13666696528,
        13339392026,
        15147010233,
        13652714550,
        17803450652,
        13946657415,
        13072337366,
        18098036596,
        17191398628,
        15768377177,
        13904100125,
        15909815940,
        13969580295,
        18967768888,
        13817476067,
        13906794765,
        13306374139,
        15647544676,
        15345881663,
        15824102265,
        18358164766,
        13684372685,
        18751982787,
        13591051770,
        13516357569,
        19974952913,
        13482805100,
        15551352540,
        18028944053,
        18273997109,
        18722404238,
        13916494571,15881036634];
    
    /**
     * 用户注册
     * @param Request $request
     * @param \app\api\model\User $user
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function register(Request $request , Member $user)
    {
        $param = $request->param();
        $redis = Redis::instance();
        $validate = new userValidate();
        if ($validate->check($param)) {
            $code = $redis->get('login_code_' . $param['mobile']);
            if($code == $param['code']) {
                $user_info = $user->getUserInfo(['mobile'=>$param['mobile']]);
                if (empty($user_info)) {
                    if(!empty($param['invite'])){
                        $invite = $user->getUserInfo(['invite'=>$param['invite']],'id');
                        if(empty($invite)){
                            return json(Config::get('code.null'));
                        }else{
                            $param['parentId'] = $invite['id'];
                        }
                    }else{
                        $result['msg'] = '请通过邀请码注册';
                        $result['status'] = 203;
                        return json($result);
                    }
                    $password = md5($param['password']);
                    $param['is_disable'] = 1;
                    $param['password'] = $password;
                    $param['mobile'] = $param['mobile'];
                    $param['invite'] = generateRandomString(6);
                    unset($param['code']);
                    if ($user->save($param)) {
                        // 同步影沐会员数据
//                        $ym_model = new YingMu();
//                        $member_info = $user->getUserInfo(['mobile'=>$param['mobile']]);
//                        $ym_model->insertYingMuMember($member_info);
                        $result = Config::get('code.success');
                    } else {
                        $result = Config::get('code.error');
                    }
                } else {
                    $result['msg'] = '该手机号已注册请登录';
                    $result['status'] = 203;
                }
            } else {
                $result = Config::get('code.codeFail');
            }
        } else {
            $result['msg'] = $validate->getError();
            $result['status'] = 203;
        }
        return json($result);
    }
    
    /**
     * 登录
     * @param Request $request
     * @param app\api\model\User $user
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function login(Request $request, Member $user) {
        $param = $request->param();
        $redis = Redis::instance();
        if (Session::has('code')) {
            $code = Session::get('code');
            if (strtolower($code) == strtolower(trim($param['code']))) {
                if ($param['mobile'] && $param['password']) {
//                    if(!in_array(intval(trim($param['mobile'])),self::LOGIN_MOBILE)){
//                        $result['status'] = 203;
//                        $result['msg'] = '您还不是VIP用户，内测阶段暂时无法登录';
//                        return json($result);
//                    }
                    $where['mobile'] = ['eq', trim($param['mobile'])];
                    $user_info = $user->getUserInfo($where);
                    if ($user_info) {
                        $password = md5(trim($param['password']));
                        if ($password == $user_info['password'] || $user_info['password'] == md5($password) || password_verify($param['password'],$user_info['password'])) {
                            Db::startTrans();
                            try {
                                $token = accessToken();
                                if (!empty($user_info['token']))
                                    $redis->hDel('user_info', $user_info['front_token']);
                                $user_info['login_time'] = time();
                                $user_info['front_token'] = $token;
                                $redis->hSet('user_info', $token, json_encode($user_info));
                                $redis->set('front_user:' . $user_info['id'], $token);
                                Session('user_id', $user_info['id']);
                                Session('isCheck', $user_info['is_check']);
                                $user->save(['front_token' => $token], ['mobile' => $param['mobile']]);
                                Session::delete('code');
                                Db::commit();
                                $result = Config::get('code.success');
                                $result['token'] = $token;
                                $result['is_check'] = $user_info['is_check'];
                                $result['mobile'] = $user_info['mobile'];
                                $result['signContract'] = $user_info['signContract'];
                                $lookintoModel = new Lookinto();
                                $lookInfo = $lookintoModel->where(['uid' => $user_info['id']])->order('create_time desc')->limit(1)->find();
                                $lookInfo = empty($lookInfo) ? array() : $lookInfo->toArray();
                                if(empty($lookInfo)){
                                    $result['member_type'] = '';
                                }else{
                                    $result['member_type'] = $lookInfo['name'];
                                }
                            } catch (\Exception $e) {
                                Db::rollback();
                                return $e->getMessage();
                            }
                        } else {
                            $result['msg'] = '密码错误';
                            $result['status'] = 203;
                        }
                    } else {
                        $result['msg'] = '该手机号未注册';
                        $result['status'] = 203;
                    }
                } else {
                    $result = Config::set('code.mistake');
                }
            } else {
                $result = Config::get('code.codeFail');
            }
        } else {
            $result = Config::get('code.codeEmpty');
        }
        return json($result);
    }

    /*
     * 获取图形验证码
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function getPicCode(Request $request)
    {
        $code = createRandomNum(4);
        Session('code',$code);
        $redis = Redis::instance();
        $redis->set('check_code',$code);
        $imageCode = new VerifyCodeImage(80,20,$code);
        $file = $imageCode->show();
        $result = Config::get('code.success');
        $result['code'] = $file;
        return json($result);
    }

    /**
     * 发送注册验证码
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function sendLoginCode(Request $request,Member $user) {
        $param = $request->param();
        $redis = Redis::instance();
//        $code = Session::get('code');
        $code = $redis->get('check_code');
        if (strtolower($code) != strtolower(trim($param['code']))) {
            return json(Config::get('code.codeFail'));
        }
        $where['mobile'] = ['eq', $param['mobile']];
        $user_info = $user->getUserInfo($where, 'id');
        if($param['type'] == 'login' && $user_info){
            return json(Config::get('code.tel'));
        }
        if($param['type'] == 'reset' && empty($user_info)){
            return json(Config::get('code.notlogin'));
        }
        $res = redisCode($param['mobile'],$param['type'].'_code_');
        if($res && !empty($param['mobile'])){
            $row = SmsToSend($param['mobile'],$res);
            if($row['code'] == 0){
                Session::delete('code');
                $result = Config::get('code.success');
            }else{
                $result['status'] = 301;
                $result['msg'] = $row['msg'];
            }
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * 验证码判断
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function judgeCode(Request $request, Member $user)
    {
        $param = $request->param();
        $redis = Redis::instance();
        $code = $redis->get('reset_code_' . $param['mobile']);
        if($param['code'] == $code){
            Session($param['mobile'],'reset');
            $result = Config::get('code.success');
        }else{
            $result = Config::get('code.codeFail');
        }
        return json($result);
    }

    /**
     * 找回密码
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function resetPwd(Request $request, Member $user)
    {
        $param = $request->param();
        $mobile = Session::get($param['mobile']);
        if (empty($param['password'])) return json( Config::get('code.error')) ;
        if($mobile == 'reset'){
            if($user->save(['password'=>md5($param['password'])],['mobile'=>$param['mobile']])){
                Session::delete($param['mobile']);
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.regetCode');
        }
        return json($result);
    }

    /**
     * 绑定手机号
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function bindMobile(Request $request, Member $user)
    {
        $param = $request->param();
        $redis = Redis::instance();
        $code = $redis->get('reset_code_' . $param['mobile']);
        if($code == $param['code']){
            $where['mobile'] = ['eq', $param['mobile']];
            $user_info = $user->getUserInfo($where);
            if($user_info){
                $result = Config::get('code.codeFail');
            }else{
                if($user->save(['mobile'=>$param['mobile']],['id'=>$user_info['id']])){
                    $result = Config::get('code.success');
                }else{
                    $result = Config::get('code.error');
                }
            }
        }else{
            $result = Config::get('code.codeFail');
        }
        return json($result);
    }

    /**
     * 退出
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function loginout(Request $request, Member $user)
    {
        $user_info = $request->user_info;
        $redis = Redis::instance();
        $res = $redis->hDel('user_info', $user_info['front_token']);
        if($res){
            Session::delete('user_id');
            $result = Config::get('code.success');
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }


    /**
     * 获取session_id
     * @param Request $request
     * @return \think\response\Json
     * @author hey_heyang(635870453@qq.com)
     */
    public function getSessionId()
    {
        if (!session_id()) session_start();
        $res = session_id();
        $result = Config::get('code.success');
        $result['session_id'] = $res;
        return json($result);
    }


}